import { getCode, login } from "../../api/user"

Page({
  data:{
    show: true,
    time: 5000,
    form: {
      mobile: '',
      code: ''
    },
    mobile: '',
    code: ''
  },
  changeMobile(e) {
    this.setData({
      'form.mobile': e.detail
    })
  },
  changeCode(e) {
    this.setData({
      'form.code': e.detail
    })
  },
  checkMobile() {
    if(this.data.form.mobile==='') {
      this.setData({
        mobile: "请输入手机号"
      })
      
    } else if(/^(?:(?:\+|00)86)?1\d{10}$/.test(this.data.form.mobile)) {
      this.setData({
        mobile: ""
      })
    } else {
      this.setData({
        mobile: "手机号格式不正确"
      })
    }
    
  },
  checkCode() {
    if(this.data.form.code==='') {
      this.setData({
        code: "请输入验证码"
      })
    } else if(this.data.form.code.length !== 6) {
      this.setData({
        code: "验证码格式不正确"
      })
    } else {
      this.setData({
        code: ""
      })
    }
    return
  },
  onSubmit() {
    if (this.data.form.mobile==='') {
      this.setData({
        mobile: "请输入手机号"
      })
    } else if (this.data.form.code==='') {
      this.setData({
        code: "请输入验证码"
      })
    }
  },

  async getCode() {
    try {
      this.checkMobile()
      if(this.data.mobile !== '请输入手机号') {
        this.setData({
          show: false
        })
        this.selectComponent('#codeBtn').start()

        const res = await getCode(this.data.form.mobile)
        wx.showToast({
          title: '发送成功',
          icon: 'success'
        })
      }
      
      
    } catch (error) {
      // wx.showToast({
      //   title: '发送失败',
      //   icon: 'error'
      // })
      console.log(error);
    }
  },
  finish() {
    this.setData({
      show: true
    })
  },
  async onLogin() {
    try {
      if (this.data.form.mobile==='') {
        this.setData({
          mobile: "请输入手机号"
        })
        
      }
      if (this.data.form.code==='') {
        this.setData({
          code: "请输入验证码"
        })
      }
      const res = await login(this.data.form)
      console.log(res);
      wx.setStorageSync('my_token', res.data)
      wx.showToast({
        title: '登录成功',
        icon: 'success'
      })
      wx.switchTab({
        url: '/pages/home/home'
      })
    } catch (error) {
      wx.showToast({
        title: '登录失败',
        icon: 'error'
      })
      console.log(error);
    }
  }
})